//
//  DetailDayViewController.m
//  Gradekeeper0.2
//
//  Created by Lily Wang on 11/17/09.
//  Copyright 2009 i5. All rights reserved.
//

#import "DetailDayViewController.h"
#import "Gradekeeper0_2AppDelegate.h"
#import "Todo.h"
#import "TodoCell.h"
#import "TKCalendarViewController.h"

@implementation DetailDayViewController
@synthesize todoView;

- (void)returnAction:(id)sender {
	[[self navigationController] popToRootViewControllerAnimated:YES];
	
} //returnAction

- (void)viewDidLoad {
	//self.toolbarItems = [NSArray arrayWithObjects: self.editButtonItem, nil];
	
	UIBarButtonItem *returnButton = [[UIBarButtonItem alloc]
									 initWithTitle:@"Return" style:UIBarButtonItemStyleBordered target:self action:@selector(returnAction:)];
	
	
	
	self.toolbarItems = [NSArray arrayWithObjects:returnButton, nil];
	
	[returnButton release];
	self.navigationItem.leftBarButtonItem = self.editButtonItem;
	
	UIBarButtonItem * btn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd 
																		  target:self action:@selector(addTodo:)];
	self.navigationItem.rightBarButtonItem = btn;
	
	taskArray = [[NSMutableArray alloc] init];
}

- (void) addTodo:(id)sender {
	Gradekeeper0_2AppDelegate *appDelegate = (Gradekeeper0_2AppDelegate *)[[UIApplication sharedApplication] delegate];
	
	if(self.todoView == nil) {
		TodoViewController *viewController = [[TodoViewController alloc] 
											  initWithNibName:@"TodoViewController" bundle:[NSBundle mainBundle]];
		self.todoView = viewController;
		[viewController release];
	}
	
	Todo *todo = [appDelegate addTodo];
	
	NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
	formatter.dateFormat = @"MM/dd/YY h:mm a";
	
	
	
	[self.navigationController setToolbarHidden:YES];
	[self.navigationController pushViewController:self.todoView animated:YES];
	
	self.todoView.todo = todo;
	self.todoView.title = todo.text;
	


	
	formatter.dateFormat = @"yyyy-MM-dd";

		
	NSDate *beginDate = [formatter dateFromString:self.title];
	NSLog(@"the begin date is %@",beginDate);
	
	NSTimeInterval secondsPerDay = 24 * 60 * 60;
	NSDate *endDate = [beginDate addTimeInterval:secondsPerDay];
	
	formatter.dateFormat = @"MM/dd/YY h:mm a";
	
	
	[self.todoView.todoText setText:todo.text];	
	[self.todoView.todoBeginDT setText:[formatter stringFromDate:beginDate]];
	[self.todoView.todoEndDT setText:[formatter stringFromDate:endDate]];
	[self.todoView.todoSummary setText:todo.summary];
	
	
	
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    // Updates the appearance of the Edit|Done button as necessary.
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:YES];
    // Disable the add button while editing.
    if (editing) {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    } else {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

-(BOOL)includeTodo:(NSDate *)beginDate:(NSDate *)endDate{
	NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDateComponents *comps = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:beginDate];
	NSString *begin= [NSString stringWithFormat:@"%i-%i-%i", [comps year], [comps month], [comps day]];	
	comps = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSWeekdayCalendarUnit) fromDate:endDate];
	
	NSString *end= [NSString stringWithFormat:@"%i-%i-%i", [comps year], [comps month], [comps day]];
	NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
	formatter.dateFormat = @"yyyy-MM-dd";
	
	if ([[formatter dateFromString:self.title] compare:[formatter dateFromString:end]] == NSOrderedDescending)
		return NO;
	
	if ([[formatter dateFromString:self.title] compare:[formatter dateFromString:begin]] == NSOrderedAscending) 
		return NO;
	
	NSLog(@"Is between");
	numberTask = numberTask + 1;
	return YES;
	
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	Gradekeeper0_2AppDelegate *appDelegate = (Gradekeeper0_2AppDelegate *)[[UIApplication sharedApplication] delegate];
	numberTask = 0;
	[taskArray removeAllObjects];
	for(int y = 0; y < appDelegate.todos.count;y++){
		Todo *todo = (Todo *)[appDelegate.todos objectAtIndex:y];
	
		if ([self includeTodo:todo.beginDate:todo.endDate]){
			NSLog(@"Yes include");
			[taskArray addObject:[NSNumber numberWithInt:y]];
			//NSLog(@"Insert into array: %d, %d", y, [[taskArray objectAtIndex:y] intValue]); 
		}
	}
//	NSLog(@"numbertTask = %d, number Todo = %d", numberTask, appDelegate.todos.count);
	return numberTask;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *MyIdentifier = @"MyIdentifier";
	
	
	TodoCell *cell = (TodoCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	
	
	if (cell == nil) {
		cell = [[[TodoCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
	}
	
	Gradekeeper0_2AppDelegate *appDelegate = (Gradekeeper0_2AppDelegate *)[[UIApplication sharedApplication] delegate];
	Todo *td = [appDelegate.todos objectAtIndex:[[taskArray objectAtIndex:indexPath.row] intValue]];
	//Todo *td = [appDelegate.todos objectAtIndex:indexPath.row];
	//NSLog(@"indexPath: %d task number: %d", indexPath.row, [[taskArray objectAtIndex:indexPath.row] intValue]);
	[cell setTodo:td];
	
	// Set up the cell
	

	return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	Gradekeeper0_2AppDelegate *appDelegate = (Gradekeeper0_2AppDelegate *)[[UIApplication sharedApplication] delegate];
	Todo *todo = (Todo *)[appDelegate.todos objectAtIndex:[[taskArray objectAtIndex:indexPath.row] intValue]];
	
	if(self.todoView == nil) {
		TodoViewController *viewController = [[TodoViewController alloc] 
											  initWithNibName:@"TodoViewController" bundle:[NSBundle mainBundle]];
		self.todoView = viewController;
		[viewController release];
	}
	
	
	[self.navigationController pushViewController:self.todoView animated:YES];
	self.todoView.todo = todo;
	self.todoView.title = todo.text;
	[self.todoView.todoText setText:todo.text];
	
	NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
	formatter.dateFormat = @"MM/dd/YY h:mm a";
	//NSString *beginDate = [formatter stringFromDate:today];
	[self.todoView.todoBeginDT setText:[formatter stringFromDate:todo.beginDate]];
	[self.todoView.todoEndDT setText:[formatter stringFromDate:todo.endDate]];
	[self.todoView.todoSummary setText:todo.summary];
	
	
	//to be deleted
	/*
	 NSInteger priority = todo.priority - 1;
	 if(priority > 2 || priority < 0) {
	 priority = 1;
	 }
	 priority = 2 - priority;
	 
	 [self.todoView.todoPriority setSelectedSegmentIndex:priority];
	 
	 if(todo.status == 1) {
	 [self.todoView.todoButton setTitle:@"Mark As In Progress" forState:UIControlStateNormal];
	 [self.todoView.todoButton setTitle:@"Mark As In Progress" forState:UIControlStateHighlighted];
	 [self.todoView.todoStatus setText:@"Complete"];
	 } else {
	 [self.todoView.todoButton setTitle:@"Mark As Complete" forState:UIControlStateNormal];
	 [self.todoView.todoButton setTitle:@"Mark As Complete" forState:UIControlStateHighlighted];
	 [self.todoView.todoStatus setText:@"In Progress"];
	 }
	 */
}



// Override if you support editing the list
- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	
	Gradekeeper0_2AppDelegate *appDelegate = (Gradekeeper0_2AppDelegate *)[[UIApplication sharedApplication] delegate];
	Todo *todo = (Todo *)[appDelegate.todos objectAtIndex:[[taskArray objectAtIndex:indexPath.row] intValue]];
	
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		[appDelegate removeTodo:todo];
		[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
	}	
}



/*
 Override if you support conditional editing of the list
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 Override if you support rearranging the list
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 Override if you support conditional rearranging of the list
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */ 

- (void)viewWillAppear:(BOOL)animated {
	[self.tableView reloadData];
	[super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
}

- (void)viewDidDisappear:(BOOL)animated {
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[super dealloc];
}


@end
